﻿namespace ChinaUnicom.Net
{
    using System;
    using Microsoft.Phone.Net.NetworkInformation;

    public sealed class NetHelper
    {
        #region constructor

        static NetHelper network;
        public static NetHelper Network { get { return network; } }

        static NetHelper()
        {
            network = new NetHelper();
        }

        private NetHelper()
        {
            /**** Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation ****/
            DeviceNetworkInformation.NetworkAvailabilityChanged += new EventHandler<NetworkNotificationEventArgs>(OnDeviceNetworkInformationNetworkAvailabilityChanged);

            IsNetworkAvailable = GetNetworkAvailabled();
        }

        #endregion

        public bool IsNetworkAvailable { get; private set; }

        public NetworkType Type { get; private set; }

        public event EventHandler<NotificationEventArgs> NetworkAvailabilityChanged;

        private void OnDeviceNetworkInformationNetworkAvailabilityChanged(object sender, NetworkNotificationEventArgs e)
        {
            switch (e.NotificationType)
            {
                case NetworkNotificationType.CharacteristicUpdate:
                case NetworkNotificationType.InterfaceConnected:
                    if (NetworkAvailabilityChanged != null)
                    {
                        IsNetworkAvailable = GetNetworkAvailabled();

                        NetworkAvailabilityChanged(this, new NotificationEventArgs(NotificationType.Availabled));
                    }
                    break;
                case NetworkNotificationType.InterfaceDisconnected:
                    if (NetworkAvailabilityChanged != null)
                    {
                        IsNetworkAvailable = GetNetworkAvailabled();

                        NetworkAvailabilityChanged(this, new NotificationEventArgs(NotificationType.Unavailabled));
                    }
                    break;
            }
        }

        bool GetNetworkAvailabled()
        {
            Type = NetworkType.Others;

            if (DeviceNetworkInformation.IsWiFiEnabled)
            {
                Type = NetworkType.Others;
            }
            else if (DeviceNetworkInformation.IsCellularDataEnabled)
            {
                Type = NetworkType.Cellular;
            }

            return DeviceNetworkInformation.IsNetworkAvailable ||
                   DeviceNetworkInformation.IsCellularDataEnabled ||
                   DeviceNetworkInformation.IsWiFiEnabled; ;
        }
    }
}
